<template>
    <div class="user-profile-page" v-if="profile">
        <!-- 个人资料头部卡片 -->
        <div class="profile-header">
            <el-card class="profile-card" :body-style="{ padding: '0' }">
                <!-- 背景区域 -->
                <div class="profile-banner" :style="{ background: getRandomGradient(profile.nickname || '') }"></div>
                <!-- 用户信息区域 -->
                <div class="profile-content">
                    <div class="profile-info-container">
                        <div class="profile-avatar">
                            <el-avatar :size="90" :src="profile.avatar"></el-avatar>
                        </div>
                        <div class="profile-info">
                            <h1 class="nickname">{{ profile.nickname }}</h1>
                            <p class="signature">{{ profile.intro || '这位用户很神秘，什么也没留下...' }}</p>
                            <div class="user-meta">
                                <div class="meta-item">
                                    <i class="far fa-calendar-alt"></i>
                                    <span>加入于 {{ formatDate(profile.createTime) }}</span>
                                </div>
                                <div class="meta-item">
                                    <i class="far fa-clock"></i>
                                    <span>最近登录 {{ formatDateTime(profile.lastLoginTime) }}</span>
                                </div>
                                <div class="meta-item">
                                    <i class="el-icon-refresh"></i>
                                    <span>最近更新 {{ profile.lastUpdateTime }}</span>
                                </div>
                                <div class="meta-item" v-if="profile.ipLocation">
                                    <i class="el-icon-location"></i>
                                    <span>{{ profile.ipLocation }}</span>
                                </div>
                                <div class="meta-item" v-if="profile.email">
                                    <i class="el-icon-message"></i>
                                    <span>{{ profile.email }}</span>
                                </div>
                            </div>
                        </div>
                        <!-- 数据统计 -->
                        <div class="stats-container">
                            <div class="stat-item">
                                <div class="stat-value">{{ profile.articleCount }}</div>
                                <div class="stat-label">文章</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value">{{ profile.totalViews }}</div>
                                <div class="stat-label">总浏览量</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value">{{ profile.totalLikes }}</div>
                                <div class="stat-label">总点赞</div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 内容区域 -->
        <div class="content-section">
            <el-row :gutter="20" class="content-row">
                <!-- 左侧统计信息 -->
                <el-col :xs="24" :sm="24" :md="6" class="stats-col">
                    <!-- 分类标签卡片 -->
                    <el-card class="categories-card" v-if="profile.categories && profile.categories.length">
                        <div slot="header" class="card-header">
                            <span>常用分类</span>
                        </div>
                        <div class="categories-wrapper">
                            <el-tag v-for="category in profile.categories" :key="category" type="success" effect="light"
                                class="category-tag" @click="selectCategory(category)">
                                <i class="el-icon-collection-tag"></i> {{ category }}
                            </el-tag>
                        </div>
                    </el-card>

                    <!-- 分类统计图表 -->
                    <el-card class="chart-card"
                        v-if="profile.categoryStats && Object.keys(profile.categoryStats).length">
                        <div slot="header" class="card-header">
                            <span>分类文章统计</span>
                        </div>
                        <div class="chart-container" id="categoryChart" ref="categoryChart"></div>
                    </el-card>
                </el-col>

                <!-- 右侧文章列表 -->
                <el-col :xs="24" :sm="24" :md="18" class="articles-col">
                    <!-- 文章分类标签页 -->
                    <el-tabs v-model="activeTab" class="content-tabs" @tab-click="handleTabClick">
                        <el-tab-pane label="全部文章" name="all"></el-tab-pane>
                        <el-tab-pane v-for="category in profile.categories" :key="category" :label="category"
                            :name="category"></el-tab-pane>
                    </el-tabs>

                    <!-- 文章列表 -->
                    <article-list :articles="processedArticles" :loading="loading" :total="currentTotal"
                        :params="params" @page-change="handlePageChange" @article-click="handleArticleClick"
                        @category-click="selectCategory" />
                </el-col>
            </el-row>
        </div>
    </div>
    <!-- 美化的骨架屏 -->
    <div v-else class="user-profile-skeleton">
        <!-- 个人资料头部骨架 -->
        <div class="profile-header skeleton-header">
            <div class="skeleton-card">
                <!-- 骨架屏背景区域 -->
                <div class="skeleton-banner shine"></div>
                <!-- 骨架屏用户信息区域 -->
                <div class="skeleton-profile-content">
                    <div class="skeleton-profile-info">
                        <!-- 头像骨架 -->
                        <div class="skeleton-avatar shine"></div>
                        <!-- 信息骨架 -->
                        <div class="skeleton-info">
                            <div class="skeleton-nickname shine"></div>
                            <div class="skeleton-signature shine"></div>
                            <div class="skeleton-meta">
                                <div class="skeleton-meta-item shine"></div>
                                <div class="skeleton-meta-item shine"></div>
                                <div class="skeleton-meta-item shine"></div>
                            </div>
                        </div>
                        <!-- 统计信息骨架 -->
                        <div class="skeleton-stats">
                            <div class="skeleton-stat-item">
                                <div class="skeleton-stat-value shine"></div>
                                <div class="skeleton-stat-label shine"></div>
                            </div>
                            <div class="skeleton-stat-item">
                                <div class="skeleton-stat-value shine"></div>
                                <div class="skeleton-stat-label shine"></div>
                            </div>
                            <div class="skeleton-stat-item">
                                <div class="skeleton-stat-value shine"></div>
                                <div class="skeleton-stat-label shine"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 内容区域骨架 -->
        <div class="skeleton-content-section">
            <div class="skeleton-row">
                <!-- 左侧骨架 -->
                <div class="skeleton-col-left">
                    <!-- 分类卡片骨架 -->
                    <div class="skeleton-categories-card">
                        <div class="skeleton-card-header shine"></div>
                        <div class="skeleton-categories-wrapper">
                            <div class="skeleton-tag shine"></div>
                            <div class="skeleton-tag shine"></div>
                            <div class="skeleton-tag shine"></div>
                            <div class="skeleton-tag shine"></div>
                        </div>
                    </div>

                    <!-- 图表卡片骨架 -->
                    <div class="skeleton-chart-card">
                        <div class="skeleton-card-header shine"></div>
                        <div class="skeleton-chart shine"></div>
                    </div>
                </div>

                <!-- 右侧骨架 -->
                <div class="skeleton-col-right">
                    <!-- 标签页骨架 -->
                    <div class="skeleton-tabs">
                        <div class="skeleton-tab-item shine"></div>
                        <div class="skeleton-tab-item shine"></div>
                        <div class="skeleton-tab-item shine"></div>
                    </div>

                    <!-- 文章列表骨架 -->
                    <div class="skeleton-article-list">
                        <div v-for="i in 3" :key="i" class="skeleton-article-item">
                            <div class="skeleton-article-cover shine"></div>
                            <div class="skeleton-article-content">
                                <div class="skeleton-article-title shine"></div>
                                <div class="skeleton-article-desc shine"></div>
                                <div class="skeleton-article-meta">
                                    <div class="skeleton-meta-item shine"></div>
                                    <div class="skeleton-meta-item shine"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { getProfile } from '@/api/profile'
import ArticleList from '@/components/ArticleList/index.vue'
import { formatTime } from '@/utils/time'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([TitleComponent, TooltipComponent, LegendComponent, PieChart, CanvasRenderer])

export default {
    name: 'UserProfile',
    metaInfo() {
        const pageTitle = this.profile ? `${this.profile.nickname}的用户主页 - 🎯 KingCola-ICG Blog` : '用户主页';
        return {
            title: pageTitle
        }
    },
    components: {
        ArticleList
    },
    data() {
        return {
            profile: null,
            loading: false,
            params: {
                pageNum: 1,
                pageSize: 10
            },
            activeTab: 'all',
            currentCategory: null,
            chart: null
        }
    },
    computed: {
        filteredArticles() {
            if (!this.profile || !this.profile.articles || !this.profile.articles.records) {
                return []
            }

            if (this.activeTab === 'all') {
                return this.profile.articles.records
            }

            return this.profile.articles.records.filter(article =>
                article.categoryName === this.activeTab
            )
        },
        processedArticles() {
            // 修复文章列表中的用户信息
            if (!this.filteredArticles.length) return [];

            return this.filteredArticles.map(article => {
                return {
                    ...article,
                    // 如果文章中用户信息为空，使用当前用户资料
                    userId: article.userId || this.profile.id,
                    nickname: article.nickname || this.profile.nickname,
                    avatar: article.avatar || this.profile.avatar
                }
            });
        },
        currentTotal() {
            if (this.activeTab === 'all') {
                return this.profile && this.profile.articles && this.profile.articles.total
                    ? this.profile.articles.total : 0
            }

            // 如果是分类筛选，计算该分类的文章数量
            return this.filteredArticles.length
        }
    },
    watch: {
        '$route.params.userId': {
            handler(newId) {
                if (newId) {
                    this.params.pageNum = 1
                    this.activeTab = 'all'
                    this.fetchUserProfile()
                }
            },
            immediate: true
        },
        profile: {
            handler() {
                this.$nextTick(() => {
                    if (this.profile && this.profile.categoryStats) {
                        this.initCategoryChart()
                    }
                })
            },
            deep: true
        }
    },
    methods: {
        formatTime,
        formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString.replace(/-/g, '/'));
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        },
        formatDateTime(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString.replace(/-/g, '/'));
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        },
        async fetchUserProfile() {
            this.loading = true
            try {
                const userId = this.$route.params.userId
                const res = await getProfile(userId, this.params)
                this.profile = res.data
            } catch (error) {
                console.error('Failed to fetch user profile:', error)
                this.$message.error('获取用户信息失败')
            } finally {
                this.loading = false
            }
        },
        handlePageChange(newPage) {
            this.params.pageNum = newPage
            this.fetchUserProfile()
        },
        handleArticleClick(articleId) {
            // 修改为post路径
            this.$router.push(`/post/${articleId}`)
        },
        handleTabClick(tab) {
            this.params.pageNum = 1
            // 如果切换了分类，重新获取数据
            if (tab.name === 'all') {
                this.fetchUserProfile()
            }
        },
        selectCategory(category) {
            this.activeTab = category
        },
        getRandomGradient(seed) {
            // 根据当前主题选择合适的渐变色
            const lightPalettes = [
                ['#a1c4fd', '#c2e9fb'], // sky blue
                ['#b2d8ff', '#eaf6ff'], // very light blue
                ['#89f7fe', '#66a6ff'], // aqua blue
                ['#c9d6ff', '#e2e2e2'], // light slate blue to grey
                ['#dbe9ff', '#a6c1ff'] // pastel blue violet
            ]

            const darkPalettes = [
                ['#355c7d', '#6c5b7b'],
                ['#2b5876', '#4e4376'],
                ['#0f2027', '#203a43'],
                ['#232526', '#414345'],
                ['#141E30', '#243B55']
            ]

            const isDark = document.documentElement.getAttribute('data-theme') === 'dark'
            const palettes = isDark ? darkPalettes : lightPalettes

            const idx = Math.abs(this.hashString(seed)) % palettes.length
            const [start, end] = palettes[idx]
            return `linear-gradient(135deg, ${start}, ${end})`
        },
        hashString(str) {
            let hash = 0
            for (let i = 0; i < str.length; i++) {
                hash = ((hash << 5) - hash) + str.charCodeAt(i)
                hash = hash & hash // Convert to 32bit integer
            }
            return Math.abs(hash)
        },
        getSexText(sex) {
            if (sex === 1) return '男'
            if (sex === 0) return '女'
            return '保密'
        },
        initCategoryChart() {
            if (!this.profile || !this.profile.categoryStats) return

            // 防止重复初始化
            if (this.chart) {
                this.chart.dispose()
            }

            const categoryStats = this.profile.categoryStats
            const chartData = Object.keys(categoryStats).map(key => ({
                name: key,
                value: categoryStats[key]
            }))

            if (chartData.length === 0) return

            const chartDom = this.$refs.categoryChart
            if (!chartDom) return

            this.chart = echarts.init(chartDom)

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    right: 10,
                    top: 'center',
                    data: chartData.map(item => item.name)
                },
                series: [
                    {
                        name: '文章分类',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 18,
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: chartData
                    }
                ]
            }

            this.chart.setOption(option)
        }
    },
    beforeDestroy() {
        if (this.chart) {
            this.chart.dispose()
            this.chart = null
        }
    }
}
</script>

<style lang="scss" scoped>
.user-profile-page {
    max-width: 1280px;
    margin: 0 auto;
    padding: $spacing-md;
}

.profile-header {
    margin-bottom: $spacing-md;
}

.profile-card {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.profile-banner {
    height: 140px;
    width: 100%;
    background-size: 400% 400%;
    animation: gradientFlow 12s ease infinite;
}

@keyframes gradientFlow {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

.profile-content {
    position: relative;
    padding: 0 $spacing-lg $spacing-md;
    margin-top: -40px;
}

.profile-info-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.profile-avatar {
    margin-right: $spacing-md;

    .el-avatar {
        border: 4px solid var(--card-bg);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
}

.profile-info {
    flex: 1;
    min-width: 200px;

    .nickname {
        font-size: 1.6em;
        font-weight: 700;
        margin: 0 0 $spacing-xs 0;
        color: var(--text-primary);
    }

    .signature {
        font-size: 0.95em;
        color: var(--text-secondary);
        margin: 0 0 $spacing-sm 0;
        font-style: italic;
    }

    .user-meta {
        display: flex;
        flex-wrap: wrap;
        gap: $spacing-sm $spacing-lg;
        font-size: 0.85em;
        color: var(--text-secondary);

        .meta-item {
            display: flex;
            align-items: center;
            gap: 5px;

            i {
                color: $primary;
            }
        }
    }
}

.stats-container {
    display: flex;
    align-items: center;
    gap: $spacing-md;
    margin-left: auto;
    padding-left: $spacing-md;
}

.stat-item {
    text-align: center;
    padding: 0 $spacing-sm;

    .stat-value {
        font-size: 1.3em;
        font-weight: 700;
        color: $primary;
    }

    .stat-label {
        font-size: 0.85em;
        color: var(--text-secondary);
    }
}

.content-section {
    margin-top: $spacing-md;
}

.content-row {
    margin: 0 -10px;
}

.stats-col {
    padding-bottom: $spacing-md;
}

.articles-col {
    padding-bottom: $spacing-md;
}

.categories-card {
    margin-bottom: $spacing-md;
    border-radius: 12px;
    overflow: hidden;

    .card-header {
        font-weight: 600;
        color: var(--text-primary);
    }

    .categories-wrapper {
        display: flex;
        flex-wrap: wrap;
        gap: $spacing-sm;
    }

    .category-tag {
        margin-bottom: 8px;
        padding: 6px 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        i {
            margin-right: 4px;
        }

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
        }
    }
}

.chart-card {
    border-radius: 12px;
    overflow: hidden;

    .card-header {
        font-weight: 600;
        color: var(--text-primary);
    }

    .chart-container {
        height: 220px;
        width: 100%;
    }
}

.content-tabs {
    background-color: var(--card-bg);
    border-radius: 8px;
    padding: $spacing-sm;
    margin-bottom: $spacing-md;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

@include responsive(md) {
    .profile-info-container {
        flex-direction: column;
        align-items: center;
    }

    .profile-avatar {
        margin-right: 0;
        margin-bottom: $spacing-md;
    }

    .profile-info {
        text-align: center;
        margin-bottom: $spacing-md;
    }

    .stats-container {
        justify-content: center;
        margin-left: 0;
        padding-left: 0;
        width: 100%;
    }

    .user-meta {
        justify-content: center;
    }
}

@include responsive(sm) {
    .user-profile-page {
        padding: $spacing-sm;
    }

    .profile-content {
        padding: $spacing-sm;
    }

    .content-section {
        margin-top: $spacing-sm;
    }

    .chart-card .chart-container {
        height: 180px;
    }
}

/* 骨架屏样式 */
.user-profile-skeleton {
    max-width: 1280px;
    margin: 0 auto;
    padding: $spacing-md;
    animation: fade-in 0.5s ease;
}

@keyframes fade-in {
    0% {
        opacity: 0;
        transform: translateY(10px);
    }

    100% {
        opacity: 1;
        transform: translateY(0);
    }
}

.skeleton-header {
    margin-bottom: $spacing-md;
}

.skeleton-card {
    border-radius: 12px;
    overflow: hidden;
    background: var(--card-bg);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.skeleton-banner {
    height: 140px;
    width: 100%;
    background: var(--hover-bg);
}

.skeleton-profile-content {
    padding: 0 $spacing-lg $spacing-md;
    margin-top: -40px;
}

.skeleton-profile-info {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.skeleton-avatar {
    width: 90px;
    height: 90px;
    border-radius: 50%;
    margin-right: $spacing-md;
    background: var(--hover-bg);
    border: 4px solid var(--card-bg);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.skeleton-info {
    flex: 1;
    min-width: 200px;
    padding: $spacing-sm 0;
}

.skeleton-nickname {
    height: 30px;
    width: 180px;
    margin-bottom: $spacing-xs;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
}

.skeleton-signature {
    height: 20px;
    width: 300px;
    margin-bottom: $spacing-sm;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
    opacity: 0.7;
}

.skeleton-meta {
    display: flex;
    flex-wrap: wrap;
    gap: $spacing-sm;
}

.skeleton-meta-item {
    height: 16px;
    width: 120px;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
    opacity: 0.6;
}

.skeleton-stats {
    display: flex;
    align-items: center;
    gap: $spacing-md;
    margin-left: auto;
    padding-left: $spacing-md;
}

.skeleton-stat-item {
    text-align: center;
    padding: 0 $spacing-sm;
}

.skeleton-stat-value {
    height: 24px;
    width: 40px;
    margin: 0 auto;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
    margin-bottom: $spacing-xs;
}

.skeleton-stat-label {
    height: 16px;
    width: 60px;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
    opacity: 0.6;
}

.skeleton-content-section {
    margin-top: $spacing-md;
}

.skeleton-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 3fr;
    gap: $spacing-md;

    @include responsive(lg) {
        grid-template-columns: 1fr;
    }
}

.skeleton-col-left {
    padding-bottom: $spacing-md;
}

.skeleton-col-right {
    padding-bottom: $spacing-md;
}

.skeleton-categories-card,
.skeleton-chart-card {
    background: var(--card-bg);
    border-radius: 12px;
    padding: $spacing-md;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
    margin-bottom: $spacing-md;
}

.skeleton-card-header {
    height: 24px;
    width: 120px;
    margin-bottom: $spacing-md;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
}

.skeleton-categories-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: $spacing-sm;
}

.skeleton-tag {
    height: 30px;
    width: 80px;
    border-radius: 15px;
    background: var(--hover-bg);
    opacity: 0.7;
}

.skeleton-chart {
    height: 220px;
    width: 100%;
    border-radius: $border-radius-md;
    background: var(--hover-bg);
    opacity: 0.6;
}

.skeleton-tabs {
    display: flex;
    background-color: var(--card-bg);
    border-radius: 8px;
    padding: $spacing-sm $spacing-md;
    margin-bottom: $spacing-md;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.skeleton-tab-item {
    height: 24px;
    width: 80px;
    margin-right: $spacing-md;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
}

.skeleton-article-list {
    display: flex;
    flex-direction: column;
    gap: $spacing-md;
}

.skeleton-article-item {
    display: flex;
    background: var(--card-bg);
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);

    @include responsive(sm) {
        flex-direction: column;
    }
}

.skeleton-article-cover {
    width: 200px;
    height: 140px;
    flex-shrink: 0;
    background: var(--hover-bg);

    @include responsive(sm) {
        width: 100%;
        height: 160px;
    }
}

.skeleton-article-content {
    flex: 1;
    padding: $spacing-md;
}

.skeleton-article-title {
    height: 28px;
    width: 80%;
    margin-bottom: $spacing-md;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
}

.skeleton-article-desc {
    height: 20px;
    width: 90%;
    margin-bottom: $spacing-sm;
    border-radius: $border-radius-sm;
    background: var(--hover-bg);
    opacity: 0.7;

    &::before {
        content: '';
        display: block;
        height: 20px;
        width: 60%;
        margin-top: $spacing-sm;
        border-radius: $border-radius-sm;
        background: var(--hover-bg);
        opacity: 0.7;
    }
}

.skeleton-article-meta {
    display: flex;
    margin-top: $spacing-md;
}

.skeleton-article-meta .skeleton-meta-item {
    height: 16px;
    width: 80px;
    margin-right: $spacing-md;
}

/* 闪光效果 */
.shine {
    position: relative;
    overflow: hidden;

    &::after {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 50%;
        height: 100%;
        background: linear-gradient(to right,
                transparent,
                rgba(255, 255, 255, 0.2),
                transparent);
        animation: shine 2s infinite;
    }
}

@keyframes shine {
    0% {
        left: -100%;
    }

    40% {
        left: 100%;
    }

    100% {
        left: 100%;
    }
}
</style>